package com.ssl;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class SslPost {
	//做host映射.linux :/etc/hosts
	private String url = "https://www.test.com:8081/BoxInfo/list";
	private String keystoreFile = "ssl/ssl.p12";
	private String keystorePwd = "123456";

	@Test
	public void post() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
			KeyManagementException {
		// RestTemplate rt = new RestTemplate(new SimpleClientHttpRequestFactory());
		// httpclient
		KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
		trustStore.load(ClassLoader.getSystemResourceAsStream(keystoreFile), keystorePwd.toCharArray());
		SSLContext sslcontext = org.apache.http.ssl.SSLContexts.custom()
				.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
		HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpclient);
		RestTemplate rt = new RestTemplate(requestFactory);
		String resp = rt.postForObject(url, null, String.class);
		System.out.println("resp:\t"+resp);
		Assert.assertNotNull(resp);
		Assert.assertEquals(resp, rt.getForObject(url, String.class));
	}
}
